package com.lechuang.member.manager.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lechuang.common.request.PageRequest;
import com.lechuang.common.result.PageResult;
import com.lechuang.common.result.Result;
import com.lechuang.common.result.ResultEnum;
import com.lechuang.member.dto.*;
import com.lechuang.member.entity.*;
import com.lechuang.member.manager.MemberManagementManager;
import com.lechuang.member.service.*;
import com.lechuang.member.vo.MemberDictCommonVo;
import com.lechuang.member.vo.MemberListVo;
import com.lechuang.member.vo.MemberVo;
import com.lechuang.user.dto.UpdateUserDto;
import com.lechuang.user.dto.UserQueryDto;
import com.lechuang.user.feign.UserFeign;
import com.lechuang.user.vo.UserDetailVo;
import com.lechuang.user.vo.UserVo;
import com.lechuang.web.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.apache.catalina.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author apple
 * @version 1.0
 * @date 2024/6/22
 */
@Service
@Log4j2
public class MemberManagementManagerImpl implements MemberManagementManager {

    @Resource
    private MemberService memberService;
    @Resource
    private MemberSummaryService memberSummaryService;

    @Resource
    private MemberLevelService memberLevelService;

    @Resource
    private MemberGroupBuyLevelService memberGroupBuyLevelService;

    @Resource
    private MemberStarLevelService memberStarLevelService;

    @Resource
    private UserFeign userFeign;


    @Override
    public PageResult<MemberListVo> memberPage(PageRequest<MemberListDto> pageRequest) {
        Page<MemberListVo> page = memberService.pageList(pageRequest);
        List<MemberListVo> records = page.getRecords();
        if (CollectionUtil.isNotEmpty(records)){
            List<Long> userIds = records.stream().map(MemberListVo::getUserId).distinct().collect(Collectors.toList());
            List<Member> memberList = memberService.queryByUserIds(userIds);
            Map<Long,Member> memberMap = memberList.stream().collect(Collectors.toMap(Member::getUserId, x -> x, (k1, k2) -> k1));
            for (MemberListVo record : records) {
                Long inviteUserId = record.getInviteUserId();
                Member member = memberMap.get(inviteUserId);
                record.setInviteUserValue(Objects.nonNull(member)?member.getNickName()+"-"+member.getPhone()
                        :StringUtils.EMPTY);
            }

        }
        //TOTO:查询当前邀请人信息
        return PageResult.result(records,page,pageRequest,null);
    }

    @Override
    public MemberVo authInfo(Long id) {
        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw  new BusinessException("未查询到会员信息");
        }
        MemberVo memberVo = BeanUtil.copyProperties(member, MemberVo.class);
        return memberVo;
    }

    @Override
    public void memberAuth(MemberAuthDto memberAuthDto) {
        Long id = memberAuthDto.getId();
        Integer authStatus = memberAuthDto.getAuthStatus();
        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw  new BusinessException("未查询到会员信息");
        }
        UserQueryDto userQueryDto =new UserQueryDto();
        userQueryDto.setId(member.getUserId());
        Result<UserVo> userVoResult = userFeign.selectById(userQueryDto);
        if (!ResultEnum.SUCCEED.getCode().equals(userVoResult.getCode())){
            throw new BusinessException(userVoResult.getMessage());
        }
        UserVo userVo = userVoResult.getData();
        if (Objects.isNull(userVo)){
            throw new BusinessException("未查询到用户信息");
        }
        Member updateMember =new Member()
                .setAuthStatus(authStatus);
        updateMember.setId(id);
        memberService.updateById(updateMember);
        UpdateUserDto updateUserDto =new UpdateUserDto()
                .setAuthStatus(authStatus)
                        .setId(userVo.getId());
        userFeign.updateUser(updateUserDto);
    }

    @Override
    public void memberActive(MemberActiveDto memberActiveDto) {
        Long id = memberActiveDto.getId();
        Integer activeStatus = memberActiveDto.getActiveStatus();
        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw  new BusinessException("未查询到会员信息");
        }
        UserQueryDto userQueryDto =new UserQueryDto();
        userQueryDto.setId(member.getUserId());
        Result<UserVo> userVoResult = userFeign.selectById(userQueryDto);
        if (!ResultEnum.SUCCEED.getCode().equals(userVoResult.getCode())){
            throw new BusinessException(userVoResult.getMessage());
        }
        UserVo userVo = userVoResult.getData();
        if (Objects.isNull(userVo)){
            throw new BusinessException("未查询到用户信息");
        }
        Member updateMember =new Member()
                .setActiveStatus(activeStatus);
        updateMember.setId(id);
        memberService.updateById(updateMember);
        UpdateUserDto userAuthDto =new UpdateUserDto()
                .setActiveStatus(activeStatus)
                .setId(userVo.getId());
         userFeign.updateUser(userAuthDto);
    }

    @Override
    public MemberListVo queryById(MemberRequestDto memberRequestDto) {
        MemberListVo  memberListVo = memberService.queryById(memberRequestDto);
        Member member = memberService.queryByUserId(memberListVo.getInviteUserId());
        memberListVo.setInviteUserValue(Objects.nonNull(member)?member.getNickName()+"-"+member.getPhone():StringUtils.EMPTY);
        return memberListVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMemberInfo(MemberRequestDto memberRequestDto) {
        Long id = memberRequestDto.getId();
        String phone = memberRequestDto.getPhone();
        String loginPassword = memberRequestDto.getLoginPassword();
        String payPassword = memberRequestDto.getPayPassword();
        String nickName = memberRequestDto.getNickName();

        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw  new BusinessException("未查询到会员信息");
        }
        Result<UserDetailVo> userDetailVoResult = userFeign.queryUserDetailByPhone(phone);
        if (!ResultEnum.SUCCEED.getCode().equals(userDetailVoResult.getCode())){
            throw new BusinessException(userDetailVoResult.getMessage());
        }
        UserDetailVo voResultData = userDetailVoResult.getData();
        //修改手机号:查询手机号是否已经注册
        if (!phone.equals(member.getPhone()) && Objects.nonNull(voResultData)){
            throw new BusinessException("该手机号已被注册");
        }
        //密码加密

        Member updateMember = new Member()
                .setNickName(nickName)
                .setPhone(phone)
                .setMemberStartLevelId(memberRequestDto.getMemberStartLevelId())
                .setMemberStartLevelName(memberRequestDto.getMemberStartLevelName())
                .setMemberLevelId(memberRequestDto.getMemberLevelId())
                .setMemberLevelName(memberRequestDto.getMemberLevelName())
                .setGroupBuyLevelId(memberRequestDto.getGroupBuyLevelId())
                .setGroupBuyLevelName(memberRequestDto.getGroupBuyLevelName())
                .setTfzEquityFlag(memberRequestDto.getTfzEquityFlag())
                .setFfzEquityFlag(memberRequestDto.getFfzEquityFlag())
                .setPreTransferPrize(memberRequestDto.getPreTransferPrize());
        if (StringUtils.isNotEmpty(payPassword)){
            //  payPassword = DigestUtils.md5Hex(payPassword);
            updateMember.setPayPassword(payPassword);
        }
        if (StringUtils.isNotEmpty(loginPassword)){
            //  loginPassword = DigestUtils.md5Hex(loginPassword);
            updateMember.setLoginPassword(loginPassword);
        }
        updateMember.setId(id);
        memberService.updateById(updateMember);
        UpdateUserDto updateUserDto = BeanUtil.copyProperties(updateMember, UpdateUserDto.class);
        updateUserDto.setId(updateMember.getUserId());
        userFeign.updateUser(updateUserDto);
    }

    @Override
    public void updateBonus(MemberBonusRequestDto memberBonusRequestDto) {
        Long id = memberBonusRequestDto.getId();
        BigDecimal totalAmount = memberBonusRequestDto.getTotalAmount();
        BigDecimal agentPrize = memberBonusRequestDto.getAgentPrize();
        BigDecimal agentPrize1 = new BigDecimal(0);
        BigDecimal selfBuyPrize = memberBonusRequestDto.getSelfBuyPrize();
        BigDecimal selfBuyPrize1 = new BigDecimal(0);
        BigDecimal servicePrize = memberBonusRequestDto.getServicePrize();
        BigDecimal servicePrize1 = new BigDecimal(0);
        BigDecimal sharePrize = memberBonusRequestDto.getSharePrize();
        BigDecimal sharePriz1 = new BigDecimal(0);
        Integer integerNum = memberBonusRequestDto.getIntegerNum();
        Integer integerNum1 = 0 ;


        MemberSummary updateMemberSummary  =new MemberSummary();
        updateMemberSummary.setMemberId(id);

        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw  new BusinessException("未查询到会员信息");
        }
        integerNum1 =member.getIntegerNum();
        MemberSummary memberSummary = memberSummaryService.queryByMemberId(id);
        if (Objects.nonNull(memberSummary)){
            agentPrize1=memberSummary.getAgentPrize();
            selfBuyPrize1 =memberSummary.getSelfBuyPrize();
            servicePrize1 = memberSummary.getServicePrize();
            sharePriz1 = memberSummary.getSharePrize();
            updateMemberSummary.setId(memberSummary.getId());
        }
        updateMemberSummary.setAgentPrize(agentPrize1);
        updateMemberSummary.setSelfBuyPrize(selfBuyPrize1);
        updateMemberSummary.setServicePrize(servicePrize1);
        updateMemberSummary.setSelfBuyPrize(selfBuyPrize1);

        Long userId = member.getUserId();
        UserQueryDto userQueryDto =new UserQueryDto();
        userQueryDto.setId(userId);
        Result<UserVo> userVoResult = userFeign.selectById(userQueryDto);
        if (!ResultEnum.SUCCEED.getCode().equals(userVoResult.getCode())){
            throw new BusinessException("用户信息查询失败:"+ userVoResult.getMessage());
        }
        UserVo userVo = userVoResult.getData();
        if (Objects.isNull(userVo)){
            throw new BusinessException("用户信息查询为空");
        }
        Member updateMember =new Member();
        UpdateUserDto updateUserDto =new UpdateUserDto();
        if (totalAmount.compareTo(userVo.getTotalAmount()) != 0){
            //修改余额
            updateMember.setTotalAmount(totalAmount);
            updateUserDto.setTotalAmount(totalAmount);
            updateMember.setId(member.getId());
            updateUserDto.setId(member.getUserId());
        }
        if (!integerNum.equals(integerNum1)){
            updateMember.setIntegerNum(integerNum);
            updateUserDto.setIntegerNum(integerNum);
            updateMember.setId(member.getId());
            updateUserDto.setId(member.getUserId());

        }
        if (agentPrize.compareTo(agentPrize1) != 0){
            updateMemberSummary.setAgentPrize(agentPrize);
        }
        if (servicePrize.compareTo(servicePrize1) != 0){
            updateMemberSummary.setServicePrize(servicePrize);
        }
        if (sharePrize.compareTo(sharePriz1) !=0){
            updateMemberSummary.setSharePrize(sharePrize);
        }
        if (selfBuyPrize.compareTo(servicePrize1) != 0){
            updateMemberSummary.setSelfBuyPrize(selfBuyPrize);
        }
        if (Objects.nonNull(updateUserDto.getId())){
            userFeign.updateUser(updateUserDto);
            memberService.updateById(updateMember);
        }

        if (Objects.isNull(updateMemberSummary.getId())){
            memberSummaryService.save(updateMemberSummary);
        }else{
            memberSummaryService.updateById(updateMemberSummary);
        }
        //TODO:记录各种明细
    }

    @Override
    public void updateWithdraw(MemberRequestDto memberRequestDto) {
        Long id = memberRequestDto.getId();
        Integer withdrawFlag = memberRequestDto.getWithdrawFlag();
        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw new BusinessException("未查询到会员信息");
        }

        Member updateMember =new Member().setWithdrawFlag(withdrawFlag);
        updateMember.setId(id);
        memberService.updateById(updateMember);
        UpdateUserDto updateUserDto =new UpdateUserDto();
        updateUserDto.setWithdrawFlag(withdrawFlag);
        updateUserDto.setId(member.getUserId());
        userFeign.updateUser(updateUserDto);
    }

    @Override
    public void updateTransfer(MemberRequestDto memberRequestDto) {
        Long id = memberRequestDto.getId();
        Integer balanceTransferFlag = memberRequestDto.getBalanceTransferFlag();
        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw new BusinessException("未查询到会员信息");
        }
        Member updateMember =new Member().setBalanceTransferFlag(balanceTransferFlag);
        updateMember.setId(id);
        memberService.updateById(updateMember);
        UpdateUserDto updateUserDto =new UpdateUserDto();
        updateUserDto.setBalanceTransferFlag(balanceTransferFlag);
        updateUserDto.setId(member.getUserId());
        userFeign.updateUser(updateUserDto);
    }

    @Override
    public void updateInviter(MemberRequestDto memberRequestDto) {
        Long id = memberRequestDto.getId();
        String newInvitePhone = memberRequestDto.getNewInvitePhone();
        Member member = memberService.getById(id);
        if (Objects.isNull(member)){
            throw  new BusinessException("未查询到会员信息");
        }
        Result<UserDetailVo> userDetailVoResult = userFeign.queryUserDetailByPhone(newInvitePhone);
        if (!ResultEnum.SUCCEED.getCode().equals(userDetailVoResult.getCode())){
            throw new BusinessException(userDetailVoResult.getMessage());
        }
        UserDetailVo inviteUserVo = userDetailVoResult.getData();
        if (Objects.isNull(inviteUserVo)){
            throw new BusinessException("新邀请人手机号未注册");
        }
        Member updatemember =new Member().setInviteUserId(inviteUserVo.getId());
        updatemember.setId(id);
        memberService.updateById(updatemember);
        UpdateUserDto updateUserDto =new UpdateUserDto().setInviteUserId(updatemember.getInviteUserId());
        updatemember.setId(member.getUserId());
        userFeign.updateUser(updateUserDto);
        //TODO:修改邀请关系表
    }

    @Override
    public MemberVo queryByUserId(Long userId) {
        MemberVo memberVo = new MemberVo();
        Member member = memberService.queryByUserId(userId);
        if (Objects.nonNull(member)){
            BeanUtil.copyProperties(member,memberVo);
        }
        return memberVo;
    }

    @Override
    public MemberDictCommonVo queryDefaultDict() {
        MemberDictCommonVo  memberDictCommonVo =new MemberDictCommonVo();
        MemberLevel memberLevel = memberLevelService.queryDefalut();
        MemberGroupBuyLevel memberGroupBuyLevel = memberGroupBuyLevelService.queryDefalut();
        MemberStarLevel memberStarLevel = memberStarLevelService.queryDefalut();
        memberDictCommonVo.setMemberLevelId(Objects.nonNull(memberLevel)?memberLevel.getId():null);
        memberDictCommonVo.setMemberLevelName(Objects.nonNull(memberLevel)?memberLevel.getName():null);
        memberDictCommonVo.setMemberStartLevelId(Objects.nonNull(memberStarLevel)?memberStarLevel.getId():null);
        memberDictCommonVo.setMemberStartLevelName(Objects.nonNull(memberStarLevel)?memberStarLevel.getName():null);
        memberDictCommonVo.setGroupBuyLevelId(Objects.nonNull(memberGroupBuyLevel)?memberGroupBuyLevel.getId():null);
        memberDictCommonVo.setGroupBuyLevelName(Objects.nonNull(memberGroupBuyLevel)?memberGroupBuyLevel.getName():null);
        return memberDictCommonVo;
    }

    @Override
    public void saveMember(SaveMemberDto saveMemberDto) {
        Long userId = saveMemberDto.getUserId();
        Member member1 = memberService.queryByUserId(userId);
        if (Objects.nonNull(member1)){
            throw new BusinessException("会员信息已存在");
        }
        Member member =new Member();
        BeanUtil.copyProperties(saveMemberDto,member);
        memberService.save(member);
    }

    @Override
    public void updateMemberByUserId(SaveMemberDto saveMemberDto) {
        Long userId = saveMemberDto.getUserId();
        Member member = memberService.queryByUserId(userId);
        if (Objects.isNull(member)){
            throw new BusinessException("未查询到会员信息");
        }
        Member updateMember = BeanUtil.copyProperties(saveMemberDto, Member.class);
        memberService.updateByUserId(updateMember);
    }
}
